package socket;

import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.StandardCharsets;

//前1024个端口号基本被系统占用，所以要使用1025以上
public class Server {
    private ServerSocket serverSocket;
    public Server(){
        try{
            System.out.println("服务器正在启动");
            serverSocket = new ServerSocket(8088);
            System.out.println("服务器启动完毕");
        }catch (IOException e){
            e.printStackTrace();
        }
    }

    /**
     * 启动服务
     */
    public void start(){
        System.out.println("服务器启动...");
        Socket socket = null;
        try {
            while (true) {
                System.out.println("等待客户端连接");
                socket = serverSocket.accept();
                System.out.println("一个客户端连接了!");
                InputStream is = socket.getInputStream();
//                int len =is.read();
//                byte[] bytes = new byte[len];
//                is.read(bytes);
//                System.out.println("客户端说：" + new String(bytes, StandardCharsets.UTF_8) );
                int d;
                while ((d=is.read())!=-1){
                    System.out.print((char) d);
                }

            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args){
        Server server = new Server();
        server.start();
    }
}
